import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

const whiteList = ['/404', '/login']

router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start()
  const { token } = store.getters
  if (token) {
    // 判断用户信息是否存在，如果不存在就调用获取用户信息接口
    if (!store.getters.name) {
      const res = await store.dispatch('user/getInfo')
      const routes = await store.dispatch('permission/filterRoutes', res.roles.menus)
      // 注意：addRoutes方法可以动态添加路由规则
      router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
      next(to.path)
    }
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  // 手动强制关闭一次  为了解决 手动切换地址时  进度条的不关闭的问题
  NProgress.done()
})

// 注意：路由跳转过后会自动触发afterEach导航守卫，在afterEach中关闭进度条
router.afterEach(() => {
  NProgress.done()
})
